<?php defined('SYSPATH') OR die('No Direct Script Access');

Class Controller_User extends Controller
{

	public function action_index() {
			

	}

	public function action_auth() {
			

		$data = arr::extract($_POST,array('name','pass'));
		$name = $data['name'];
		$pass = $data['pass'];
		$user = ORM::factory('user')->where('name','=',$name)->find();
		if ($user->pass == md5($pass)){


			$coocietoken = md5(microtime());
			$sqltoken = md5($coocietoken.$_SERVER["REMOTE_ADDR"]);

			$user->token = $sqltoken;
			$user->save();
			Cookie::set('token', $coocietoken, 3600*24*7);
			echo "OK";


		}
		else{
			echo "NOK";
		}
	}

	public function action_logoff() {
			
		Helper_User::logoff();
		$this->request->redirect('/');
	}

	public function action_subscribe($id){

		//берем id залогиненного админа
		$userid = ORM::factory('user')
		->where('fullname','=',Helper_User::get_logged())
		->find();

		//устанавливаем подписку админа на тикет
		$result = ORM::factory('subscriber');
		$result->admin_id = $userid;
		$result->ticket_id = $id;

		//сохраняем подписку
		$result->save();

		echo 'OK';

	}

	public function action_unsubscribe($id){

		//берем id залогиненного админа
		$userid = ORM::factory('user')
		->where('fullname','=',Helper_User::get_logged())
		->find();

		//ищем подписку админа на тикет
		$results = ORM::factory('subscriber')
		->where('admin_id','=',$userid)
		->where('ticket_id','=',$id)
		->find_all();

		foreach ($results as $result) {
			//удаляем подписку
			$result->delete();
		}


		echo 'OK';

	}
}